import { computed, getCurrentInstance, reactive, ref, watch } from 'vue';
import { AudioControl } from '../../type';

export default function(props, { emit }, audioRef) {
  const {
    proxy
  } = getCurrentInstance();
  const currentAudio = reactive<AudioControl>({
    // 原始数据
    origin: {
      resource: {
        name: '', // 资源名称
        url: '' // 资源访问地址
      }
    },
    // 现在播放时的数据
    data: {
      currentTime: 0, // 当前时间
      maxTime: 0, // 最长时间
      playing: false,
      muted: false,
      speed: 1,
      waiting: true,
      preload: 'auto',
      processTime: 0, // 当前进度
      volume: 100 // 音量
    }
  })
  // 进度条拖拽事件
  const isDraging = ref<boolean>(false);
  /**
   * 当前时间的转换
   */
  const currentTimeComputed = computed(() => {
    return methods.newSecondToHour(currentAudio.data.currentTime);
  })
  /**
   * 最大时间的转换
   */
  const maxTimeComputed = computed(() => {
    return methods.newSecondToHour(currentAudio.data.maxTime);
  })
  const playTimeInput = ref<string>('00:00.00');
  /**
   * 当前输入框显示的播放时间（可修改）
   */
  const playTime = computed({
    get() {
      return methods.newSecondToHour(currentAudio.data.currentTime);
    },
    set(val: string) {
      playTimeInput.value = val;
    }
  })
  watch(() => props.audioData, val => {
    currentAudio.origin = val;
  }, {
    deep: true,
    immediate: true
  })
  const methods = {
    /**
     * 秒（精确到百分秒） 转 分:秒.毫秒
     * @param second {string} '65.32'
     * @returns {string} '01:05.32'
     * @constructor
     */
    newSecondToHour(second) {
      if (second > 0) {
        second = second + '';
        let t = '';
        let millisecond = '00';
        const hasMillisecond = second.split('.').length > 1;
        if (hasMillisecond) {
          millisecond = String(second).split('.')[1].slice(0, 2);
        }
        const min = Math.floor(second / 60);
        const sec = Math.floor(second % 60);
        if (min < 10) {
          t += 0;
        }
        t += `${min}:`;
        if (sec < 10) {
          t += 0;
        }
        t += `${sec}.`;
        return `${t}${millisecond}`;
      }
      return '00:00.00';
    },
    /**
    * 时分秒转化为秒 保留百分秒
    * @param time('01:05.32')
    * @returns {number} '65.32'
    */
    newTranslateToSecond(times) {
      const timeArr = times.split(':');
      const min = Number(timeArr[0])
      const sec = Number(timeArr[1].split('.')[0])
      const mill = Number(timeArr[1].split('.')[1])
      return (min * 60 + sec) + '.' + mill
    },
    /**
     * 音频播放器播放事件
     * @param res
     */
    onPlay(res) {
      currentAudio.data.playing = true;
      const target = res.target;
      const audios = document.getElementsByTagName('audio');
      // 当前播放时，全局的播放器都停止播放
      [...audios].forEach((item) => {
          if (item !== target) {
              item.pause();
          }
      });
    },
    onError() {
      currentAudio.data.waiting = true;
    },
    onWaiting() {
    },
    onPause() {
      currentAudio.data.playing = false;
    },
    /**
     * 播放器进度更新
     * @param res
     */
    onTimeupdate(res) {
      if (!isDraging.value) {
          // 更新当前时间
        currentAudio.data.currentTime = res.target.currentTime;
        // 更新进度条
        currentAudio.data.processTime = currentAudio.data.currentTime / currentAudio.data.maxTime * 100;
        playTime.value = methods.newSecondToHour(res.target.currentTime)
        emit('timeupdate', currentAudio.data.currentTime)
      }
    },
    /**
     * 当加载语音流元数据完成后，会触发该事件的回调函数
     * 语音元数据主要是语音的长度之类的数据
     * @param res
     */
    onLoadedmetadata(res) {
      currentAudio.data.waiting = false;
      currentAudio.data.maxTime = parseInt(res.target.duration);
    },
    /**
     * 播放控制
     * @returns
     */
    playControl() {
      if (currentAudio.origin.resource.url) {
        if (currentAudio.data.waiting) {
          proxy.$message.warning('当前音频暂时无法播放');
          return;
        }
        currentAudio.data.playing ? methods.pause() : methods.play();
      } else {
        proxy.$message.warning('当前暂无音频播放');
      }
    },
    play() {
      audioRef.value.play();
    },
    pause() {
      audioRef.value.pause();
    },
    /**
     * 手动拖拽进度条改变时间
     * @param e
     */
    changeProcessTime(e) {
      currentAudio.data.processTime = e;
      audioRef.value.currentTime = currentAudio.data.maxTime / 100 * e;
      methods.play();
    },
    /**
     * 快退5秒, 然后继续播放
     */
    quickPrev() {
      audioRef.value.currentTime -= 5;
      methods.play();
    },
    /**
     * 快进5秒, 然后继续播放
     */
    quickNext() {
      audioRef.value.currentTime += 5;
      methods.play();
    },
    /**
     * 进度条消息提示
     * @param time 当前进度
     * @returns
     */
    formatToolTip(time) {
      const process = currentAudio.data.maxTime / 100 * time;
      return '当前进度: ' + methods.newSecondToHour(process);
    },
    /**
     * 输入时间的格式校验
     */
    validateTime() {
      let flag = true;
      const reg = /^(\d+):(\d{2})\.(\d{2})$/
      if (!playTimeInput.value.match(reg)) {
        proxy.$message.warning('请输入正确的时间格式，例如: 01:10.10');
        flag = false;
      }
      return flag
    },
    /**
     * 跳转到指定时间点
     */
    changeTime() {
      // 第一步还得检测传入时间点格式对不对
      const validate = methods.validateTime();
      if (validate) {
        // 第二步将 00:00.00 转换成秒
        audioRef.value.currentTime = methods.newTranslateToSecond(playTimeInput.value);
        methods.play()
      }
    },
    /**
     * 音量提示
     */
    formatVolumnToolTip(volume) {
      return '当前音量：' + volume + '%';
    },
    /**
     * 禁音/开启声音
     */
    changeVolumnMuted() {
      audioRef.value.muted = !audioRef.value.muted;
      currentAudio.data.muted = audioRef.value.muted;
      if (!audioRef.value.muted) {
        methods.changeVolumn(50);
      } else {
        methods.changeVolumn(0);
      }
    },
    /**
     * 修改音量
     */
    changeVolumn(volume) {
      const volumnVal = volume / 100;
      currentAudio.data.volume = volume;
      audioRef.value.volume = volumnVal;
      if (volume === 0) {
        audioRef.value.muted = true;
        currentAudio.data.muted = true;
      } else {
        audioRef.value.muted = false;
        currentAudio.data.muted = false;
      }
    }
  }
  return {
    methods,
    currentAudio,
    currentTimeComputed,
    maxTimeComputed,
    playTime,
    playTimeInput,
    isDraging
  }
}
